﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.SessionState;

namespace RDIFramework.WebApp.Modules.handler
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.WebCommon;
    using RDIFramework.Utilities;
    using RDIFramework.ServiceAdapter;

    /// <summary>
    /// UserAdminHandler 的摘要说明
    /// </summary>
    public class UserAdminHandler : IHttpHandler, IRequiresSessionState
    {
        string PermissionItemScopeCode = "Resource.ManagePermission";

        private string action
        {
            get
            {
                return RDIFramework.WebCommon.PublicMethod.GetString(getObj("action"));
            }
        }

        private object getObj(string key) { return RDIFramework.WebCommon.StringHelper.GetRequestObject(key); }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            switch (action)
            {    
                case "edit":
                    EditUser(context);
                    break;
                case "delete":
                    DeleteUser(context);
                    break;
                case "add":
                    AddUser(context);
                    break;
                case "setpassword":
                    SetUserPassword(context);
                    break;
                case "GetUserListByPage":
                    GetUserListByPage(context);
                    break;
                case "GetDTByRole": //按角色获取用户列表
                    GetDTByRole(context);
                    break;
                case "AddUserToRole":
                    AddUserToRole(context); //为指定用户批量添加角色
                    break;
                case "RemoveRoleByUserId": //批量移除角色
                    RemoveRoleByUserId(context);
                    break;
                default:
                    string json = RDIFramework.WebCommon.JSONhelper.ToJson(this.GetUserScopeList(PermissionItemScopeCode));
                    context.Response.Write(json);                    
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        //每页的记录数
        private int pagesize { get { return PublicMethod.GetInt(getObj("rows")); } }
        //当前请求第几页
        private int pageindex { get { return PublicMethod.GetInt(getObj("page")); } }
        //排序字段
        public string sortName { get { return PublicMethod.GetString(getObj("sort")); } }
        //排序方式
        public string sortType { get { return PublicMethod.GetString(getObj("order")); } }

        /// <summary>
        /// 是否有相应的权限
        /// </summary>
        /// <param name="permissionItemCode">权限编号</param>
        /// <returns>是否有权限</returns>
        private bool IsAuthorized(string permissionItemCode, string permissionItemName = null)
        {
            RDIFrameworkService RDIFrameworkService = new RDIFrameworkService();
            UserInfo user = Utils.UserInfo;
            return RDIFrameworkService.PermissionService.IsAuthorizedByUserId(user, user.Id, permissionItemCode, permissionItemName);
        }

        /// <summary>
        /// 得到分页用户列表
        /// </summary>
        /// <param name="ctx"></param>
        private void GetUserListByPage(HttpContext ctx)
        {
            string where = "";
            string filters = PublicMethod.GetString(getObj("filter"));
            if (filters != "")
            {
                string grouptype;
                IList<SearchFilter> list = SearchFilter.GetSearchList(filters, out grouptype);
                where = SearchFilter.ToSql(list, grouptype);
            }


            int _pageindex = 1;
            int _pagesize = 20;

            if (pageindex > 0)
                _pageindex = pageindex;
            if (pagesize > 0)
                _pagesize = pagesize;
            int recordCount = 0;
            DataTable dtUser = RDIFramework.ServiceAdapter.RDIFrameworkService.Instance.UserService.GetDTByPage(Utils.UserInfo, out recordCount, _pageindex, _pagesize, where, (sortName + " " + sortType));
            string json = RDIFramework.WebCommon.JSONhelper.FormatJSONForEasyuiDataGrid(recordCount,dtUser);
            ctx.Response.Write(json);
        }

        /// <summary>
        /// 获取用户权限域数据
        /// </summary>
        private DataTable GetUserScopeList(string permissionItemScopeCode)
        {
            // 是否有用户管理权限，若有用户管理权限就有所有的用户类表，这个应该是内置的操作权限
            bool userAdmin = false;
            userAdmin = this.IsAuthorized("UserAdmin");
            DataTable returnValue = new DataTable(PiUserTable.TableName);
            UserInfo user = Utils.UserInfo;
            // 获取用户数据
            if (userAdmin)
            {
                if (user.IsAdministrator || (String.IsNullOrEmpty(permissionItemScopeCode) || (!SystemInfo.EnableUserAuthorizationScope)))
                {
                    returnValue = RDIFrameworkService.Instance.UserService.GetDT(user);
                }
                else
                {
                    returnValue = RDIFrameworkService.Instance.PermissionService.GetUserDTByPermissionScope(user, user.Id, permissionItemScopeCode);
                }

            }
            return returnValue;
        }

        /// <summary>
        /// 按角色获取用户列表
        /// </summary>
        /// <param name="ctx"></param>
        private void GetDTByRole(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleId"));
            string writeJson = "[]";
            if (!string.IsNullOrEmpty(roleId))
            {
                writeJson = RDIFramework.WebCommon.JSONhelper.ToJson(RDIFrameworkService.Instance.UserService.GetDTByRole(Utils.UserInfo, roleId));
            }
            ctx.Response.Write(writeJson);
        }

        /// <summary>
        /// 为指定用户批量添加角色
        /// </summary>
        /// <param name="ctx"></param>
        private void AddUserToRole(HttpContext ctx)
        {
            string userId = PublicMethod.GetString(getObj("userId"));
            string addRoleIds = PublicMethod.GetString(getObj("addRoleIds"));
            if (!string.IsNullOrEmpty(addRoleIds) && addRoleIds.Trim().Length > 0)
            {
                int returnValue = RDIFrameworkService.Instance.UserService.AddUserToRole(Utils.UserInfo, userId, addRoleIds.Split(','));
                if (returnValue > 0)
                {
                    ctx.Response.Write("1");
                }
                else
                {
                    ctx.Response.Write("添加角色失败！");
                }
            }
        }

        /// <summary>
        /// 批量移除角色
        /// </summary>
        /// <param name="ctx"></param>
        private void RemoveRoleByUserId(HttpContext ctx)
        {
            string userId = PublicMethod.GetString(getObj("userId"));
            string removeRoleIds = PublicMethod.GetString(getObj("removeRoleIds"));
            if (!string.IsNullOrEmpty(removeRoleIds) && removeRoleIds.Trim().Length > 0)
            {
                int returnValue = RDIFrameworkService.Instance.UserService.RemoveUserFromRole(Utils.UserInfo, userId, removeRoleIds.Split(','));
                if (returnValue > 0)
                {
                    ctx.Response.Write("1");
                }
                else
                {
                    ctx.Response.Write("移除角色失败！");
                }
            }
        }

        private void AddUser(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            PiUserEntity entity = new PiUserEntity();
            entity.UserName = PublicMethod.GetString(getObj("UserName"));
            entity.RealName = PublicMethod.GetString(getObj("RealName"));
            string pwd  = PublicMethod.GetString(getObj("UserPassword"));
            entity.UserPassword = pwd == string.Empty ? string.Empty : pwd;
            entity.Gender = PublicMethod.GetString(getObj("Gender"));
            entity.Mobile = PublicMethod.GetString(getObj("Mobile"));
            entity.Birthday = PublicMethod.GetDateTime(getObj("Birthday"));
            entity.Telephone = PublicMethod.GetString(getObj("Telephone"));
            entity.Title = PublicMethod.GetString(getObj("Title"));
            entity.Duty = PublicMethod.GetString(getObj("Duty"));
            entity.QICQ = PublicMethod.GetString(getObj("QICQ"));
            entity.Email = PublicMethod.GetString(getObj("Email"));
            string vCompanyName = PublicMethod.GetString(getObj("vCompanyName"));
            string vDepartmentName = PublicMethod.GetString(getObj("vDepartmentName"));
            string vWorkgroupName = PublicMethod.GetString(getObj("vWorkgroupName"));
            entity.CompanyName = vCompanyName == "请选择" ? string.Empty : vCompanyName;
            entity.DepartmentName = vDepartmentName == "请选择" ? string.Empty : vDepartmentName;
            entity.WorkgroupName = vWorkgroupName == "请选择" ? string.Empty : vWorkgroupName;
            entity.HomeAddress = PublicMethod.GetString(getObj("HomeAddress"));
            entity.Enabled = PublicMethod.GetString(getObj("Enabled")) == "on" ? 1 : 0;
            entity.Description = PublicMethod.GetString(getObj("Description"));
            entity.RoleId = PublicMethod.GetInt(getObj("vRoleId"));
            entity.CompanyId = PublicMethod.GetInt(getObj("vCompanyId"));
            entity.DepartmentId = PublicMethod.GetInt(getObj("vDepartmentId"));
            entity.WorkgroupId = PublicMethod.GetInt(getObj("vWorkgroupId"));                
            entity.OpenId = BusinessLogic.NewGuid();
            if (vUser != null)
            {
                entity.CreateBy = vUser.RealName;
                entity.CreateUserId = vUser.Id;
            }

                string statusCode = string.Empty;
                string statusMessage = string.Empty;
                //增加用户
                string vReturnValue = RDIFrameworkService.Instance.UserService.AddUser(vUser, entity, out statusCode, out statusMessage);
                if (statusCode == StatusCode.OKAdd.ToString())
                {
                    ctx.Response.Write("1");
                }
                else
                {
                    ctx.Response.Write(statusMessage);
                }
        }

        private void EditUser(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("id"));
            PiUserEntity entity = RDIFrameworkService.Instance.UserService.GetEntity(vUser, vId);
            if (entity != null)
            {
                entity.UserName = PublicMethod.GetString(getObj("UserName"));
                entity.RealName = PublicMethod.GetString(getObj("RealName"));
                entity.Code = PublicMethod.GetString(getObj("Code"));
                entity.Gender = PublicMethod.GetString(getObj("Gender"));
                entity.Mobile = PublicMethod.GetString(getObj("Mobile"));
                entity.Birthday = PublicMethod.GetDateTime(getObj("Birthday"));
                entity.Telephone = PublicMethod.GetString(getObj("Telephone"));
                entity.Title = PublicMethod.GetString(getObj("Title"));
                entity.Duty = PublicMethod.GetString(getObj("Duty"));
                entity.QICQ = PublicMethod.GetString(getObj("QICQ"));
                entity.Email = PublicMethod.GetString(getObj("Email"));
                string vCompanyName = PublicMethod.GetString(getObj("vCompanyName"));
                string vDepartmentName = PublicMethod.GetString(getObj("vDepartmentName"));
                string vWorkgroupName = PublicMethod.GetString(getObj("vWorkgroupName"));
                entity.CompanyName = vCompanyName == "请选择" ? string.Empty : vCompanyName;
                entity.DepartmentName = vDepartmentName== "请选择" ? string.Empty : vDepartmentName;
                entity.WorkgroupName = vWorkgroupName == "请选择" ? string.Empty : vWorkgroupName;
                entity.HomeAddress = PublicMethod.GetString(getObj("HomeAddress"));
                entity.Enabled = PublicMethod.GetString(getObj("Enabled")) == "on" ? 1 : 0;
                entity.Description = PublicMethod.GetString(getObj("Description"));
                entity.RoleId = PublicMethod.GetInt(getObj("vRoleId"));
                entity.CompanyId = PublicMethod.GetInt(getObj("vCompanyId"));
                entity.DepartmentId = PublicMethod.GetInt(getObj("vDepartmentId"));
                entity.WorkgroupId = PublicMethod.GetInt(getObj("vWorkgroupId"));          
                if (vUser != null)
                {
                    entity.ModifiedBy = vUser.RealName;
                    entity.ModifyUserId = vUser.Id;
                }

                try
                {
                    string statusCode = string.Empty;
                    string statusMessage = string.Empty;
                    RDIFrameworkService.Instance.UserService.UpdateUser(vUser, entity, out statusCode, out statusMessage);
                    if (statusCode == StatusCode.OKUpdate.ToString())
                    {
                        if (SystemInfo.ShowInformation)
                        {
                            ctx.Response.Write("1");
                        }
                    }
                    else
                    {
                        ctx.Response.Write(statusMessage);
                    }
                }
                catch (Exception ex)
                {
                    ctx.Response.Write("更新用户失败!");
                }
            }
        }

        private void DeleteUser(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("id"));
            int vReturnValue = RDIFrameworkService.Instance.UserService.SetDeleted(vUser,new string[]{vId});
            if (vReturnValue > 0)
            {
                ctx.Response.Write("1");
            }
            else
            {
                ctx.Response.Write("删除用户失败！");
            }
        }

        private void SetUserPassword(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("id"));
            string vNewPwd = PublicMethod.GetString(getObj("password"));
            
            string statusCode = string.Empty;
            string statusMessage = string.Empty;
            RDIFrameworkService.Instance.LogOnService.SetPassword(vUser, new string[] { vId }, vNewPwd, out statusCode, out statusMessage);
          
            if (statusCode == StatusCode.SetPasswordOK.ToString())
            {
              ctx.Response.Write("1");
            }
            else
            {
                ctx.Response.Write(statusMessage);
            }
        }
    }
}